//
//  BlogDetailViewModel.swift
//  mmda
//
//  Created by 李陆涛 on 2018/8/10.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit

class BlogDetailViewModel: NSObject {

    var blog:Blog?
    
    var comments: NSMutableArray = NSMutableArray()
    
    
//    var loadFinished: ((_ error: String?,_ isloadMore:Bool) -> Void)?
    
    var loadFinished: ((_ error: String?) -> Void)?
    
    
    func reloadData() {
        
        
        page = 1
        reloadBlogDdetail()
        getMoreComment()
    }
    
    private func reloadBlogDdetail() {
        
        guard let bid = blog?._id else { return }
        
        NetAPI.blogdetail(bid: bid).request(Blog.self,dealJson: "blog") {
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            guard let blog = response as? Blog else {
                
                self.loadFinished?(errmsg)
                return
            }
            
            self.blog = blog
            self.loadFinished?(nil)
        }
    }
    
    private var page:Int = 1
    
    func getMoreComment() {
        
        guard let bid = blog?._id else { return }
        
        NetAPI.allcomment(bid: bid, page: page).request([Comment].self, dealJson: "comments") {
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            guard let response = response as? [Comment] else {
                
                self.loadFinished?(errmsg)
                
                return
            }
            
            if self.page == 1 {
                self.comments.removeAllObjects()
            }
            
            self.comments.addObjects(from: response)
            self.loadFinished?(nil)
            
            self.page = self.page + 1
        }
    }
}
